package com.xpjhs.login;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.xpjhs.user.model.User;
import com.xpjhs.util.DigestUtils;

@Controller
@RequestMapping
public class LoginController {
	@RequestMapping("/login")
	public String login(HttpServletRequest request, ModelMap model) {
		return "admin.login";
	}
	@RequestMapping("/logout")
	public void logout(){
		
	}

	/**
	 * 用户登录
	 * 
	 * @param username
	 * @param password
	 * @param request
	 * @param model
	 * @return
	 * @throws IOException
	 */
	@RequestMapping(value = "/login", method = RequestMethod.POST)
	public String login(User user, HttpServletRequest request, ModelMap model)
			throws IOException {
		UsernamePasswordToken token = new UsernamePasswordToken(
				user.getUsername(), DigestUtils.md5(user.getPassword()));
		token.setRememberMe(true);
		Subject subject = SecurityUtils.getSubject();
		try {
			subject.login(token);
		} catch (Exception e) {
			model.addAttribute("loginInfo", "帐号或密码错误！！！");
			return "admin.login";
		}

		return "admin.index";
	}

	/**
	 * 首页
	 * 
	 * @return
	 */
	@RequestMapping("/index")
	public String index() {
		return "/index";
	}
}
